package com.jinlejia.erp.ui.mine.contract;


import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jinlejia.erp.R;
import com.jinlejia.erp.bean.AttachBean;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.weight.CustomToast;
import com.jinlejia.erp.utils.DownloadUtil;
import com.jinlejia.erp.utils.IntenetUtil;

import com.jinlejia.erp.utils.MimeType;
import com.jinlejia.erp.widget.ButtonCircleProgressBar;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import java.io.File;
import java.util.ArrayList;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

/**
 * A simple {@link Fragment} subclass.
 * 附件
 */
public class AttachFragment extends Fragment {

    private View view;
    private RecyclerView recyclerView;
    private SlimAdapter slimAdapter;

    public AttachFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_attach, null);
            initView();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    private void initView() {
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setHasFixedSize(true);

        slimAdapter = SlimAdapter.create()
                .register(R.layout.item_attach_layout, new SlimInjector<AttachBean>() {
                    @Override
                    public void onInject(final AttachBean data, IViewInjector injector) {
                        injector.text(R.id.name, data.getAttachName())
                                .with(R.id.progressBar, (IViewInjector.Action<ButtonCircleProgressBar>) mProgressBar -> {

                                    String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator).concat("JljAttach").concat(File.separator)
                                            .concat(data.getAttachUrl().substring(data.getAttachUrl().lastIndexOf("/")));

                                    if (new File(path).exists()) {
                                        data.setNativePath(path);
                                        mProgressBar.setStatus(ButtonCircleProgressBar.Status.END);
                                        mProgressBar.setTag(data.getNativePath());
                                    } else {
                                        mProgressBar.setStatus(ButtonCircleProgressBar.Status.START);
                                        mProgressBar.setTag("");
                                    }
                                })
                                .clicked(R.id.enclosure_layout, v -> {
                                    final ButtonCircleProgressBar mProgressBar = (ButtonCircleProgressBar) v.findViewById(R.id.progressBar);
                                    if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.LOADING) {
                                        //下载中，停止下载
                                        mProgressBar.setStatus(ButtonCircleProgressBar.Status.START);
                                        DownloadUtil.get().cancelTag(data.getAttachUrl());

                                    } else if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.START) {
                                        //初始状态，开始下载
                                        if (IntenetUtil.getNetworkState(getActivity()) == IntenetUtil.NETWORN_WIFI) {
                                            //wifi环境直接下载
                                            downLoad(mProgressBar, data);
                                        } else {
                                            //移动网络提示是否继续下载
                                            CommonDialog dialog = new CommonDialog(getActivity(), "提示", "当前为移动网络，是否继续?", "继续", "取消");
                                            dialog.show();
                                            dialog.setConfirmListener(() -> downLoad(mProgressBar, data));
                                        }

                                    } else if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.END) {
                                        //已经下载，直接查看
                                        openFile(mProgressBar.getTag().toString());
                                    }
                                });
                    }
                }).attachTo(recyclerView);

    }

    public void setData(ArrayList<AttachBean> data) {
        slimAdapter.updateData(data);
    }

    private void downLoad(final ButtonCircleProgressBar mProgressBar, final AttachBean data) {
        mProgressBar.setStatus(ButtonCircleProgressBar.Status.LOADING);
        DownloadUtil.get().download(data.getAttachUrl(), "JljAttach", data.getAttachUrl(), new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(ButtonCircleProgressBar.Status.END);
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator).concat("JljAttach")
                                        .concat(data.getAttachUrl().substring(data.getAttachUrl().lastIndexOf("/")));
                                mProgressBar.setTag(path);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloading(final int progress) {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(ButtonCircleProgressBar.Status.LOADING);
                                mProgressBar.setProgress(progress);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloadFailed() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(() -> mProgressBar.setStatus(ButtonCircleProgressBar.Status.START))
                        .subscribe();
            }
        });
    }

    private void openFile(String path) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        File file = new File(path);
        //获取文件file的MIME类型
        String type = MimeType.getMIMEType(file);
        //设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            CustomToast.showToast(getActivity(), "您没有可以打开该文件的应用!", 1500);
        }
    }

}
